package com.wjjun.basemvpvm.databinding.adapter;

import android.databinding.BindingAdapter;
import android.text.InputFilter;
import android.text.InputType;
import android.widget.EditText;
import android.widget.TextView;

import com.wjjun.basemvpvm.utils.EmojiInputFilter;
import com.wjjun.basemvpvm.utils.RangeInputFilter;

/**
 * author Wjjun
 * Created 2018/3/14.
 */
public class EditTextAdapter {

    @BindingAdapter(value = "imeOptions")
    public static void setImeOptions(EditText editText, TextView.OnEditorActionListener listener) {
        editText.setOnEditorActionListener(listener);
    }

    @BindingAdapter(value = {"maxValue", "minValue"}, requireAll = false)
    public static void setValueRange(EditText editText, final double maxValue, final double minValue) {
        if (maxValue < minValue) {
            return;
        }

        InputFilter[] filters;
        int length = 0;
        InputFilter[] exitFilters = editText.getFilters();
        if (exitFilters != null) {
            length = exitFilters.length;
            filters = new InputFilter[length + 1];
            for (int i = 0; i < length; i++) {
                filters[i] = exitFilters[i];
            }
        } else {
            filters = new InputFilter[1];
        }

        filters[length] = new RangeInputFilter(maxValue, minValue);
        editText.setFilters(filters);
    }

    /**
     * 是否允许输入emoji
     */
    @BindingAdapter(value = "emoji", requireAll = false)
    public static void setEmojiAble(EditText editText, boolean able) {
        if (able) {
            return;
        }

        InputFilter[] filters = new InputFilter[1];
        int length = 0;
        InputFilter[] exitFilters = editText.getFilters();
        if (exitFilters != null) {
            length = exitFilters.length;
            filters = new InputFilter[length + 1];
            for (int i = 0; i < length; i++) {
                filters[i] = exitFilters[i];
            }
        }

        filters[length] = new EmojiInputFilter();
        editText.setFilters(filters);
    }
}
